package com.suneee.trades.init;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.suneee.base.util.JsonUtil;
import com.suneee.base.util.MD5Utils;
import com.suneee.core.util.DateUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.quartz.entity.TmallOrderEn;
import com.suneee.quartz.init.TmallInterface;
import com.suneee.shop.entity.Shop;
import com.suneee.trades.entity.PromotionDetails;
import com.suneee.trades.entity.TradesInfo;
import com.suneee.trades.entity.TradesOrder;
import com.suneee.trades.resource.OfflineStatus;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.PromotionDetail;
import com.taobao.api.domain.Trade;
import com.taobao.api.response.TradeFullinfoGetResponse;

public class TradesInfoInitialization {

	/**
	 * 初始化交易信息
	 * @param tradeList
	 * @param tmallOrderEn
	 * @return
	 * @throws Exception
	 */
	public static TmallOrderEn initTradesInfo(List<Trade> tradeList,TmallOrderEn tmallOrderEn) throws Exception{
		TmallOrderEn returnOrderEn = new TmallOrderEn();
		List<TradesInfo> tradesInfoList = new ArrayList<TradesInfo>();
		List<TradesOrder> tradesOrderList = new ArrayList<TradesOrder>();
		List<PromotionDetails> promotionDetailsList = new ArrayList<PromotionDetails>();
		
		for (Trade trade : tradeList) {
			TradesInfo initTradesInfo = initTrades(tmallOrderEn, trade.getTid());
			
			if(initTradesInfo.getIsSuccess()){
				tradesInfoList.add(initTradesInfo); //得到交易主表信息
				
				List<TradesOrder> forOrderList = initTradeOrder(initTradesInfo);//得到当前交易子订单信息
				List<PromotionDetails> forPromotionList = initPromotionDetails(initTradesInfo);//得到当前交易优惠信息	
				
				tradesOrderList.addAll(forOrderList);
				promotionDetailsList.addAll(forPromotionList);
			}
		}
		returnOrderEn.setTradesInfoList(tradesInfoList);
		returnOrderEn.setTradesOrderList(tradesOrderList);
		returnOrderEn.setPromotionDetailsList(promotionDetailsList);
		
		return returnOrderEn;
	}
	
	//初始化交易主表信息
	public static TradesInfo initTrades(TmallOrderEn tmallOrderEn,Long tid) throws Exception{
		//在此根据交易id获取Tmall交易详细信息
		//StringBuffer remarkStr = new StringBuffer();
		TradeFullinfoGetResponse fullRsp = TmallInterface.getfullinfoOrder(tmallOrderEn,tid);
		Trade fullTrade = fullRsp.getTrade();
		TradesInfo tradesInfo =new TradesInfo();
		//  TRADE_NO_CREATE_PAY(没有创建支付宝交易) * WAIT_BUYER_PAY(等待买家付款) TRADE_CLOSED_BY_TAOBAO(付款以前，卖家或买家主动关闭交易)  不同步
		if(fullTrade != null && !fullTrade.getStatus().equals("WAIT_BUYER_PAY") && !fullTrade.getStatus().equals("TRADE_NO_CREATE_PAY") && !fullTrade.getStatus().equals("TRADE_CLOSED_BY_TAOBAO")){
			tradesInfo.setIsSuccess(true);
			tradesInfo.setTid(fullTrade.getTid().toString());
			tradesInfo.setShopId(tmallOrderEn.getShopId());
			tradesInfo.setEnterpriseCode(tmallOrderEn.getEnterpriseCode());
			tradesInfo.setSellerNick(fullTrade.getSellerNick());
			tradesInfo.setBuyerNick(fullTrade.getBuyerNick());
			tradesInfo.setTitle(fullTrade.getTitle());
			tradesInfo.setType(fullTrade.getType());
			tradesInfo.setPicPath(fullTrade.getPicPath());
			tradesInfo.setTradeFrom(fullTrade.getTradeFrom());
			tradesInfo.setShippingType(fullTrade.getShippingType());
			tradesInfo.setReceiverName(fullTrade.getReceiverName());
			tradesInfo.setReceiverCountry(fullTrade.getReceiverCountry());
			tradesInfo.setReceiverState(fullTrade.getReceiverState());
			tradesInfo.setReceiverCity(fullTrade.getReceiverCity());
			tradesInfo.setReceiverDistrict(fullTrade.getReceiverDistrict());
			tradesInfo.setReceiverTown(fullTrade.getReceiverTown());
			tradesInfo.setReceiverAddress(fullTrade.getReceiverAddress());
			tradesInfo.setReceiverZip(fullTrade.getReceiverZip());
			tradesInfo.setReceiverMobile(fullTrade.getReceiverMobile());
			tradesInfo.setReceiverPhone(fullTrade.getReceiverPhone());
			if(!StringUtils.isEmpty(fullTrade.getTotalFee()))
					tradesInfo.setTotalFee(new BigDecimal(fullTrade.getTotalFee()));
			if(!StringUtils.isEmpty(fullTrade.getPostFee()))
				tradesInfo.setPostFee(new BigDecimal(fullTrade.getPostFee()));
			if(!StringUtils.isEmpty(fullTrade.getReceivedPayment()))
				tradesInfo.setReceivedPayment(new BigDecimal(fullTrade.getReceivedPayment()));
			if(!StringUtils.isEmpty(fullTrade.getPayment()))
				tradesInfo.setPayment(new BigDecimal(fullTrade.getPayment()));
			if(fullTrade.getHasPostFee() != null)
				tradesInfo.setHasPostFee(fullTrade.getHasPostFee());
			if(!StringUtils.isEmpty(fullTrade.getDiscountFee()))
				tradesInfo.setDiscountFee(new BigDecimal(fullTrade.getDiscountFee()));
			if(!StringUtils.isEmpty(fullTrade.getAdjustFee()))
				tradesInfo.setAdjustFee(new BigDecimal(fullTrade.getAdjustFee()));
			tradesInfo.setInvoiceName(fullTrade.getInvoiceName());
			tradesInfo.setInvoiceType(fullTrade.getInvoiceType());
			tradesInfo.setInvoiceKind(fullTrade.getInvoiceKind());
			if(fullTrade.getCreated() != null)
				tradesInfo.setCreated(DateUtils.getTimestamp(fullTrade.getCreated()));
			if(fullTrade.getPayTime() != null)
				tradesInfo.setPayTime(DateUtils.getTimestamp(fullTrade.getPayTime()));
			if(fullTrade.getModified() != null)
				tradesInfo.setModified(DateUtils.getTimestamp(fullTrade.getModified()));
			if(fullTrade.getEndTime() != null)
				tradesInfo.setEndTime(DateUtils.getTimestamp(fullTrade.getEndTime()));
			tradesInfo.setBuyerMessage(fullTrade.getBuyerMessage());
			tradesInfo.setBuyerMemo(fullTrade.getBuyerMemo());
			if (!StringUtils.isEmpty(tradesInfo.getBuyerMessage())) {
				tradesInfo.setRemark("买家有备注");
			} else {
				tradesInfo.setRemark("无备注");
			}
			if(fullTrade.getBuyerFlag() != null)
				tradesInfo.setBuyerFlag(fullTrade.getBuyerFlag().intValue());
			tradesInfo.setSellerMemo(fullTrade.getSellerMemo());
			if(fullTrade.getSellerFlag() != null)
				tradesInfo.setSellerFlag(fullTrade.getSellerFlag().intValue());
			if(fullTrade.getTimeoutActionTime() != null)
				tradesInfo.setTimeoutActionTime(DateUtils.getTimestamp(fullTrade.getTimeoutActionTime()));
			tradesInfo.setStatus(fullTrade.getStatus());
			tradesInfo.setEstConTime(fullTrade.getEstConTime());
			
			tradesInfo.setIs_Locked(false);
			tradesInfo.setTradeType("系统");
			tradesInfo.setSplitStatus("");
			tradesInfo.setAuditTime(DateUtils.getCurrentTimestamp());//审单时间
			tradesInfo.setFullTrade(fullTrade); //把当前查询到的交易主对象赋值进去，供后续查询用
		}else{
			tradesInfo.setIsSuccess(false);
		}
		return tradesInfo;
	}
	
	//初始化交易订单行信息
	public static List<TradesOrder> initTradeOrder(TradesInfo paramTradesInfo) throws Exception{
		List<TradesOrder> initradesOrderList = new ArrayList<TradesOrder>();
		//交易订单行
		List<Order> initOrdersList = paramTradesInfo.getFullTrade().getOrders();//服务子订单列表
		for (Order order : initOrdersList) {
			TradesOrder inittradesOrder = new TradesOrder();
			
			inittradesOrder.setOid(order.getOid().toString());
			inittradesOrder.setTid(paramTradesInfo.getTid());
			inittradesOrder.setPicPath(order.getPicPath());
			inittradesOrder.setItemMealName(order.getItemMealName());
			inittradesOrder.setRefundStatus(order.getRefundStatus());
			inittradesOrder.setOuterIid(order.getOuterIid());
			inittradesOrder.setSnapshotUrl(order.getSnapshotUrl());
			inittradesOrder.setSnapshot(order.getSnapshot());
			inittradesOrder.setTimeoutActionTime(order.getTimeoutActionTime());
			inittradesOrder.setBuyerRate(order.getBuyerRate()); 
			inittradesOrder.setSellerRate(order.getSellerRate()); 
			inittradesOrder.setCid(order.getCid().toString()); 
			inittradesOrder.setStatus(order.getStatus()); 
			inittradesOrder.setTitle(order.getTitle());
			inittradesOrder.setType(order.getType());
			inittradesOrder.setPrice(order.getPrice().toString()); 
			inittradesOrder.setNumIid(order.getNumIid().toString()); 
			if(order.getItemMealId() != null && order.getItemMealId() != 0)
				inittradesOrder.setItemMealId(order.getItemMealId().toString());
			inittradesOrder.setSkuId(order.getSkuId().toString()); 
			if(order.getNum() !=null)
				inittradesOrder.setNum(order.getNum().intValue()); 
			inittradesOrder.setOuterSkuId(order.getOuterSkuId()); 
			inittradesOrder.setOrderFrom(order.getOrderFrom()); 
			inittradesOrder.setTotalFee(order.getTotalFee()); 
			inittradesOrder.setPayment(order.getPayment()); 
			inittradesOrder.setDiscountFee(order.getDiscountFee()); 
			inittradesOrder.setAdjustFee(order.getAdjustFee()); 
			inittradesOrder.setModified(order.getModified()); 
			inittradesOrder.setSkuPropertiesName(order.getSkuPropertiesName()); 
			if(order.getRefundId() !=null)
				inittradesOrder.setRefundId(order.getRefundId().intValue() + ""); 
			inittradesOrder.setIsOversold(order.getIsOversold()); 
			inittradesOrder.setEndTime(order.getEndTime()); 
			if(!StringUtils.isEmpty(order.getConsignTime()) && order.getIsShShip()!= null && order.getIsShShip())
				inittradesOrder.setConsignTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(order.getConsignTime())); 
			if(!StringUtils.isEmpty(order.getPartMjzDiscount()))
				inittradesOrder.setPartMjzDiscount(new BigDecimal(order.getPartMjzDiscount())); 
			inittradesOrder.setDiscountFee(order.getDiscountFee()); 
			
			initradesOrderList.add(inittradesOrder); //子订单
		}
		
		return initradesOrderList;
		
	}

	//初始化优惠详细信息
	public static List<PromotionDetails> initPromotionDetails(TradesInfo paramTradesInfo){
		List<PromotionDetails> promotionDetailsList = new ArrayList<PromotionDetails>();
		/** 查询优惠详细信息 */
		List<PromotionDetail> promotionDetailList = paramTradesInfo.getFullTrade().getPromotionDetails(); 
		if(promotionDetailList != null){
			for (PromotionDetail promotionDetail : promotionDetailList) {
				PromotionDetails entity = new PromotionDetails();
				entity.setTid(paramTradesInfo.getTid());
				entity.setOrderId(promotionDetail.getId().toString());
				entity.setPromotionName(promotionDetail.getPromotionName());
				if(!StringUtils.isEmpty(promotionDetail.getDiscountFee()))
					entity.setDiscountFee(new BigDecimal(promotionDetail.getDiscountFee()));
				entity.setGiftItemName(promotionDetail.getGiftItemName());
				entity.setGiftItemId(promotionDetail.getGiftItemId());
				if(!StringUtils.isEmpty(promotionDetail.getGiftItemNum()))
					entity.setGiftItemNum(Integer.valueOf(promotionDetail.getGiftItemNum()));
				entity.setPromotionDesc(promotionDetail.getPromotionDesc());
				entity.setPromotionId(promotionDetail.getPromotionId());
				promotionDetailsList.add(entity);
			}
		}
	    return promotionDetailsList;
	}
	
	///**理单，查找可合并信息 **/
	public static Map<String,List<String>> richardTrades(List<TradesInfo> insertTradList){
		Map<String,List<String>> mapL = new HashMap<String, List<String>>();
		TradesInfo temp = null;
		for (int i = 0; i < insertTradList.size(); i++) {
			temp = insertTradList.get(i);
			String md5Key = MD5Utils.md5( temp.getReceiverName()+
					temp.getReceiverCountry()+temp.getReceiverState()+temp.getReceiverCity()+temp.getReceiverDistrict()+
					temp.getReceiverTown()+temp.getReceiverAddress()+temp.getReceiverMobile());
			if(mapL.get(md5Key) == null){
				List<String> listStr = new ArrayList<String>();
				listStr.add(temp.getTid());
				mapL.put(md5Key, listStr);
			}else{
				List<String> listStr = mapL.get(md5Key);
				if(!listStr.contains(temp.getTid())){
					listStr.add(temp.getTid());
				}
			}
		}
		return mapL;
	}
	
	///** 组装交易对应的行数据  **/
	public static Map<String,List<TradesOrder>> assembleTradesOrder(List<TradesOrder> insertOrderList){
		Map<String,List<TradesOrder>> mapOrder = new HashMap<String, List<TradesOrder>>();
		TradesOrder temp = new TradesOrder();
		List<TradesOrder> odlist = null;
		for (int i = 0; i < insertOrderList.size(); i++) {
			temp = insertOrderList.get(i);
			String key = temp.getTid();
			if(mapOrder.get(key) == null){
				odlist = new ArrayList<TradesOrder>();
				odlist.add(temp);
				mapOrder.put(key, odlist);
			}else{
				odlist = mapOrder.get(key);
				if(!odlist.contains(temp.getTid())){
					odlist.add(temp);
				}
			}
		}
		return mapOrder;
	}
	
	///** 组装交易优惠信息数据  **/
	public static Map<String,List<PromotionDetails>>  assemblePromotion(List<PromotionDetails> insertPromotionDetailsList){
		Map<String,List<PromotionDetails>> mapPromtion = new HashMap<String, List<PromotionDetails>>();
		PromotionDetails prtemp = new PromotionDetails();
		List<PromotionDetails> prList = null;
		for (int i = 0; i < insertPromotionDetailsList.size(); i++) {
			prtemp = insertPromotionDetailsList.get(i);
			String key = prtemp.getTid();
			if(mapPromtion.get(key) == null){
				prList = new ArrayList<PromotionDetails>();
				prList.add(prtemp);
				mapPromtion.put(key, prList);
			}else{
				prList = mapPromtion.get(key);
				if(!prList.contains(prtemp.getTid())){
					prList.add(prtemp);
				}
			}
		}
		return mapPromtion;
	}
	
	///** 获取单个交易信息 **/
	public static TmallOrderEn getOneTradesInfo(Shop shopEn,TmallOrderEn entity) throws Exception{
		List<TradesInfo> tradesInfoList = new ArrayList<TradesInfo>();
		List<TradesOrder> tradesOrderList = new ArrayList<TradesOrder>();
		List<PromotionDetails> promotionDetailsList = new ArrayList<PromotionDetails>();
		TmallOrderEn tmallOrderEn = new TmallOrderEn();
		Map<String,String> shopMap = JsonUtil.parse(shopEn.getRuleInfo());
		shopMap.put("proxUrl", shopEn.getProxyURL());
		tmallOrderEn.setShopMap(shopMap);
		tmallOrderEn.settId(entity.gettId());//界面传过来的交易号
		tmallOrderEn.setShopId(shopEn.getShopId());
		tmallOrderEn.setEnterpriseCode(shopEn.getEnterpriseCode());
		
		TradesInfo initTradesInfo = initTrades(tmallOrderEn, Long.valueOf(entity.gettId()));
		if(initTradesInfo.getIsSuccess()){
			
			tmallOrderEn.setIsSuccess(true);
			
			initTradesInfo.setOfflineStatus(OfflineStatus.REVIEW_ORDER.name());
			tradesInfoList.add(initTradesInfo);
			tradesOrderList = initTradeOrder(initTradesInfo);
			promotionDetailsList = initPromotionDetails(initTradesInfo);
			
			Map<String,List<PromotionDetails>> mapPromtion = assemblePromotion(promotionDetailsList);
			Map<String,List<TradesOrder>> mapOrder = assembleTradesOrder(tradesOrderList);
			tmallOrderEn.setTradesInfoList(tradesInfoList);
			tmallOrderEn.setTradesOrderList(tradesOrderList);
			tmallOrderEn.setMapPromtion(mapPromtion);
			tmallOrderEn.setMapOrder(mapOrder);
			
			tmallOrderEn.setTotalRows(1L);
		}else{
			tmallOrderEn.setIsSuccess(false);
			tmallOrderEn.setTotalRows(0L);
		}
		return tmallOrderEn;
	}
}
